import { useEffect, useState } from "react";
import "./index.less";
import { } from '@uiw/react-amap'
import AMapLoader from "@amap/amap-jsapi-loader";

// @ts-ignore
window._AMapSecurityConfig = {
  securityJsCode: "2cd59db9f0385f7d0f5c036966ea34a7",
}

interface Props {
  getAddress: (address: object) => any;
  initialLng?: string;
  initialLat?: string;
  mapRef: any;
}

const DaemonMap: React.FC<Props> = (props) => {
  const { getAddress, initialLng, initialLat, mapRef } = props;
  let map: any = null;
  const [markerList, setMarkerList] = useState<any[]>([]);


  const createMarker = (lng?: number, lat?: number) => {
    if (!lng || !lat) {
      return;
    }

    // @ts-ignore
    const marker = new AMap.Marker({
      icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
      // @ts-ignore
      position: new AMap.LngLat(lng, lat)
    });

    markerList.forEach((item: any) => {
      map.remove(item);
    });

    // @ts-ignore
    const geoCoder = new AMap.Geocoder({});
    geoCoder.getAddress([lng, lat], (status: any, result: any) => {
      if (status === 'complete' && result.regeocode) {
        const address = result.regeocode.formattedAddress;
        console.log('点击位置信息：', result.regeocode.formattedAddress);
        const adcode = result.regeocode.addressComponent.adcode
        //   let reg = /.+?(省|市|自治区|自治州|县|区)/g
        const provinceId = parseInt(adcode.substr(0, 2) + '0000')
        const cityId = parseInt(adcode.substr(0, 4) + '00')
        const areaId = adcode
        console.log('点击位置的省市区id：', provinceId, cityId, areaId);
        getAddress({ addressDetail: address, lngLat: { lng: lng, lat: lat } });
      }
    });

    marker.setMap(map);
    markerList.push(marker);
    console.log(lng);
  }

  const handleMapClick = (event: any) => {
    if (!event?.lnglat) {
      return;
    }

    const { lng, lat } = event?.lnglat;
    createMarker(lng, lat);
  };

  useEffect(() => {
    AMapLoader.load({
      key: "dc7888f1a1ea7d43b39e8c16b46536f9", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ["AMap.Geocoder", "AMap.PlaceSearch"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
      .then((AMap) => {
        let centerLng = initialLng, centerLat = initialLat;
        if (!initialLng) {
          centerLng = "113.758886";
        }

        if (!initialLat) {
          centerLat = "23.025474";
        }
        map = new AMap.Map("container", {
          // 设置地图容器id
          viewMode: "3D", // 是否为3D地图模式
          zoom: 11, // 初始化地图级别
          center: [centerLng, centerLat], // 初始化地图中心点位置
        });

        if (initialLng && initialLat) {
          createMarker(parseFloat(initialLng), parseFloat(initialLat));
          map.setCenter([initialLng, initialLat]);
        }
        map.on('click', handleMapClick);
      })
      .catch((e) => {
        console.log(e);
      });

    return () => {
      map?.destroy();
    };
  }, []);

  return (
    <div
      ref={mapRef}
      id="container"
      className='container'
      style={{ height: "400px" }}
      onClick={handleMapClick}
    ></div>
  );
}

export default DaemonMap;
